﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderManagementAPI.Data;
using OrderManagementAPI.Models;
using System.Runtime.InteropServices;

namespace OrderManagementAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly OrderContext _context;

        public OrdersController(OrderContext context)
        {
            _context = context;
        }

        // GET: api/Orders
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Order>>> GetOrders(
            [FromQuery] string? customer,
            [FromQuery] string? productName,
            [FromQuery] decimal? minAmount,
            [FromQuery] decimal? maxAmount)
        {
            var query = _context.Orders.Include(o => o.Details).AsQueryable();

            if (!string.IsNullOrEmpty(customer))
                query = query.Where(o => o.Customer.Contains(customer));

            if (!string.IsNullOrEmpty(productName))
                query = query.Where(o => o.Details.Any(d => d.ProductName.Contains(productName)));

            if (minAmount.HasValue)
                query = query.Where(o => o.Details.Sum(d => d.Price * d.Quantity) >= minAmount);

            if (maxAmount.HasValue)
                query = query.Where(o => o.Details.Sum(d => d.Price * d.Quantity) <= maxAmount);

            return await query.ToListAsync();
        }

        // GET: api/Orders/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Order>> GetOrder(int id)
        {
            var order = await _context.Orders
                .Include(o => o.Details)
                .FirstOrDefaultAsync(o => o.OrderId == id);

            if (order == null)
            {
                return NotFound();
            }

            return order;
        }

        // POST: api/Orders
        [HttpPost]
        public async Task<ActionResult<Order>> PostOrder(Order order)
        {
            if (await _context.Orders.AnyAsync(o => o.OrderId == order.OrderId))
                return BadRequest("订单已存在");

            _context.Orders.Add(order);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetOrder", new { id = order.OrderId }, order);
        }

        // PUT: api/Orders/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutOrder(int id, Order order)
        {
            if (id != order.OrderId)
                return BadRequest("ID不匹配");

            var existingOrder = await _context.Orders
                .Include(o => o.Details)
                .FirstOrDefaultAsync(o => o.OrderId == id);

            if (existingOrder == null)
                return NotFound();

            // 更新订单基本信息
            _context.Entry(existingOrder).CurrentValues.SetValues(order);

            // 处理订单明细
            foreach (var detail in order.Details)
            {
                var existingDetail = existingOrder.Details
                    .FirstOrDefault(d => d.Id == detail.Id);

                if (existingDetail != null)
                    _context.Entry(existingDetail).CurrentValues.SetValues(detail);
                else
                    existingOrder.Details.Add(detail);
            }

            // 删除不存在于新数据中的明细
            foreach (var existingDetail in existingOrder.Details.ToList())
            {
                if (!order.Details.Any(d => d.Id == existingDetail.Id))
                    _context.OrderDetails.Remove(existingDetail);
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!OrderExists(id))
                    return NotFound();
                else
                    throw;
            }

            return NoContent();
        }

        // DELETE: api/Orders/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteOrder(int id)
        {
            var order = await _context.Orders.FindAsync(id);
            if (order == null)
            {
                return NotFound();
            }

            _context.Orders.Remove(order);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool OrderExists(int id)
        {
            return _context.Orders.Any(e => e.OrderId == id);
        }
    }
}